package com.hduong.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by dudu on 2020/3/18.
 */
@Component
public class MyLb implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     *  自旋锁 ： 其实就是锁  控制线程安全的
     *  CAS 算法 调用的 cpu指令
     * @return
     */
    public final int getAndIncrement() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            //2147483647
            next = current == Integer.MAX_VALUE ? 0 : current + 1;
            //当前值 和 预期修改值
            //内存值如果没有被其他线程修改 说明没有问题
        }while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("******** next : " + next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();

        return serviceInstances.get(index);
    }
}
